package com.rmondjone.utils

import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.os.Build
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.Display
import android.view.WindowManager


/**
 * copyright：
 * @author：anthui creation date： 2020/11/17.
 * @since: 1.0.0
 * @describe：安卓尺寸相关转换工具
 */

//获取系统的测量工具
private val metrics = Resources.getSystem().displayMetrics

/**
 * copyright：
 * @author：anthui creation date： 2020/11/17.
 * @since: 2.7.8
 * @describe: dp 转为 px
 */
val Float.dp: Float
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, this,
        metrics
    )
val Int.dp: Float
    get() = this.toFloat().dp


/**
 * copyright：
 * @author：anthui creation date： 2020/11/17.
 * @since: 2.7.8
 * @describe: sp转为 dp
 */

val Float.sp: Float
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP, this,
        metrics
    )

val Int.sp: Float
    get() = this.toFloat().sp


val Float.pxToDp: Float
    get() {
        TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_PX, this,
            metrics
        )
        return 1f
    }


/**
 * copyright：
 * @author：anthui creation date： 2020/11/17.
 * @since: 2.7.8
 * @describe:px转为 dp
 * */
val Float.toDp
    get() = this / (if (metrics.density <= 0) 1f else metrics.density)


val Int.toDp get() = this.toFloat().toDp


val Float.toSp get() = this / (if (metrics.scaledDensity <= 0) 1f else metrics.scaledDensity)
val Int.toSp get() = this.toFloat().toSp


//屏幕 宽度 px
val screenWidth get() = metrics.widthPixels

//屏幕高度 px
val screenHeight get() = metrics.heightPixels

fun Context.screenRealHeight() {
    var display: Display? = null
    //适配新版
//    if (this is Activity && Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
//        display = this.display
//    }
    if (display == null) {
        val windowManager =
            this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        //Q开始 使用 context.getDisplay
        display = windowManager.defaultDisplay
    }
    val dm = DisplayMetrics()
    display?.getRealMetrics(dm)

    dm.heightPixels
}

